const express = require("express");
const router = express.Router();
const querySql = require("./db/index");
const result = require("./model/result");
const checkJwt = require("./utils/checkJwt");
const { encrypt, decrypt } = require("./utils/jwt");
const queryCount = require("./utils/queryCount");

router.get("/", (req, res) => {
  res.send("Hello girls or boys,service is run success!");
});
router.get("/login", async (req, res) => {
  // console.log(req.query); //get请求
  const { username, password } = req.query;
  // const userlist = await querySql("select * from user");
  const exitAccount = await querySql(
    `select * from user where username='${username}'`
  );
  if (exitAccount.length > 0) {
    const isUser = await querySql(
      `select id,username from user where username='${username}' and password='${password}'`
    );
    if (isUser.length <= 0) {
      return res.send(new result([], "账号或密码错误", 405));
    } else {
      let token = encrypt({ username, password }, 24 * 60 * 60);
      return res.send(new result({ ...isUser[0], token }, "登录成功", 200));
    }
  } else {
    return res.send(new result([], "不存在该用户,请先注册", 404));
  }
});

router.get("/route", async (req, res) => {
  const { id } = req.query;
  const token = req.headers.authorization;
  const jwtStatus = checkJwt(token);
  if (jwtStatus instanceof result) {
    return res.send(jwtStatus);
  } else {
    const user = await querySql(
      `select id,role from user where username='${jwtStatus}'`
    );
    if (id != user[0].id) {
      res.send(new result({}, "请勿使用他人token进行验证,请重新登录", 406));
    } else {
      const { role } = user[0];
      const [{ menu, children }] = await querySql(
        `select menu,children from role where id='${role}'`
      );
      // 角色对应的菜单
      const menuList = await querySql(
        `select * from main_menu where id in (${menu})`
      );
      // 对应的子菜单
      const chimenu = await querySql(
        `select * from sub_menu where id in (${children})`
      );
      // 根据角色对应的menu子菜单进行添加
      menuList.map(menu => {
        menu.children = [];
        chimenu.reduce((preval, val) => {
          if (val.parentId == menu.id) {
            preval.push(val);
          }
          return preval;
        }, menu.children);
        return menu;
      });
      res.send(new result(menuList, "获取成功", 200));
    }
  }
});
router.post("/userinfo", async (req, res) => {
  const token = req.headers.authorization;
  const tokenStatus = decrypt(token);
  if (tokenStatus.token) {
    const { username } = req.body;
    const userInfo = await querySql(
      `select * from user where username= '${username}'`
    );
    return res.send(new result(...userInfo, "获取成功", 200));
  } else {
    return res.send(new result(tokenStatus.info, "验证错误", 401));
  }
});
router.post("/alluser", async (req, res) => {
  const token = req.headers.authorization;
  const tokenStatus = decrypt(token);
  if (tokenStatus.token) {
    let screen = Object.keys(req.body).filter(
      item => item != "page" && item != "psize" && item != "create_time"
    );
    let condition = screen
      .filter(item => req.body[item] !== "")
      .map(item => `${item} like'%${req.body[item]}%'`)
      .join(" and ");
    let showpage = (req.body.page - 1) * req.body.psize;
    let showlimit = parseInt(req.body.psize);
    const user = await querySql(
      !!condition
        ? `select * from user where ${condition} limit ${showpage},${showlimit}`
        : `select * from user limit ${showpage},${showlimit}`
    );
    const count = await queryCount("user", condition);
    return res.send(new result({ data: user, count: count }, "获取成功", 200));
  } else {
    return res.send(new result(tokenStatus.info, "验证错误", 401));
  }
});

router.post("/alldepartment", async (req, res) => {
  const token = req.headers.authorization;
  const tokenStatus = decrypt(token);
  if (tokenStatus.token) {
    let screen = Object.keys(req.body).filter(
      item => item != "page" && item != "psize" && item != "create_time"
    );
    let condition = screen
      .filter(item => req.body[item] !== "")
      .map(item => `${item} like'%${req.body[item]}%'`)
      .join(" and ");
    let showpage = (req.body.page - 1) * req.body.psize;
    let showlimit = parseInt(req.body.psize);
    const department = await querySql(
      !!condition
        ? `select * from department where ${condition} limit ${showpage},${showlimit}`
        : `select * from department limit ${showpage},${showlimit}`
    );
    const count = await queryCount("department", condition);
    return res.send(
      new result({ data: department, count: count }, "获取成功", 200)
    );
  } else {
    return res.send(new result(tokenStatus.info, "验证错误", 401));
  }
});

router.post("/allrole", async (req, res) => {
  const token = req.headers.authorization;
  const tokenStatus = decrypt(token);
  if (tokenStatus.token) {
    let screen = Object.keys(req.body).filter(
      item => item != "page" && item != "psize" && item != "create_time"
    );
    let condition = screen
      .filter(item => req.body[item] !== "")
      .map(item => `${item} like'%${req.body[item]}%'`)
      .join(" and ");
    let showpage = (req.body.page - 1) * req.body.psize;
    let showlimit = parseInt(req.body.psize);
    const role = await querySql(
      !!condition
        ? `select * from role where ${condition} limit ${showpage},${showlimit}`
        : `select * from role limit ${showpage},${showlimit}`
    );
    const count = await queryCount("role", condition);
    return res.send(new result({ data: role, count: count }, "获取成功", 200));
  } else {
    return res.send(new result(tokenStatus.info, "验证错误", 401));
  }
});
router.post("/allmenu", async (req, res) => {
  const token = req.headers.authorization;
  const tokenStatus = decrypt(token);
  if (tokenStatus.token) {
    let screen = Object.keys(req.body).filter(
      item => item != "page" && item != "psize" && item != "create_time"
    );
    let condition = screen
      .filter(item => req.body[item] !== "")
      .map(item => `${item} like'%${req.body[item]}%'`)
      .join(" and ");
    let showpage = (req.body.page - 1) * req.body.psize;
    let showlimit = parseInt(req.body.psize);
    const main_menu = await querySql(
      !!condition
        ? `select * from main_menu where ${condition} limit ${showpage},${showlimit}`
        : `select * from main_menu limit ${showpage},${showlimit}`
    );
    for (let i = 0; i < main_menu.length; i++) {
      const sql = `select * from sub_menu where parentId = ${main_menu[i].id}`;
      const submenu = await querySql(sql);
      main_menu[i].children = submenu;
    }
    const count = await queryCount("main_menu", condition);
    return res.send(
      new result({ data: main_menu, count: count }, "获取成功", 200)
    );
  } else {
    return res.send(new result(tokenStatus.info, "验证错误", 401));
  }
});
router.post("/addRole", async (req, res) => {
  const token = req.headers.authorization;
  const tokenStatus = decrypt(token);
  if (tokenStatus.token) {
    const { name, menu, children, intro } = req.body;
    const role = await querySql(
      `insert into role (name,menu,children,intro) values ('${name}','${menu}','${children}','${intro}')`
    );
    return res.send(new result(role, "添加成功", 200));
  } else {
    return res.send(new result(tokenStatus.info, "验证错误", 401));
  }
});
router.post("/getMenuByRoleId", async (req, res) => {
  const token = req.headers.authorization;
  const tokenStatus = decrypt(token);
  if (tokenStatus.token) {
    const { menu, children } = req.body;
    // 角色对应的菜单
    const menuList = await querySql(
      `select * from main_menu where id in (${menu})`
    );
    // 对应的子菜单
    const chimenu = await querySql(
      `select * from sub_menu where id in (${children})`
    );
    // 根据角色对应的menu子菜单进行添加
    menuList.map(menu => {
      menu.children = [];
      chimenu.reduce((preval, val) => {
        if (val.parentId == menu.id) {
          preval.push(val);
        }
        return preval;
      }, menu.children);
      return menu;
    });
    res.send(new result(menuList, "获取成功", 200));
  }
});
// 编辑的路由
module.exports = router;
